<?php
/**
 * User: Bryant Byrd
 * Date: 3/10/11 12:41 PM
 */

require_once ( SLOG_UTILITIES_PATH . "SimpleDOM.php" );

class Scouters_Log_Database {
    public function __construct () {
    }

    const SLOG_DB_PREFIX = "slog_";
    const SLOG_LATEST_DB_VERSION = 5;
    const SLOG_DB_VERSION_OPTION_NAME = "slog_db_version";

    static function db_setup () {
        $activeDbVersion = self::get_db_version();
        error_log( "Active DB Version: ". $activeDbVersion );
        // Perform database updates only if needed
        if ( $activeDbVersion < self::SLOG_LATEST_DB_VERSION ) {
            $scriptDom = simpledom_load_file(
                realpath( str_replace( ".php", "_Upgrade_Scripts.xml", __FILE__ ) ) );
            $scriptNodes = $scriptDom->sortedXPath(
                "slog_sql_script[@id > " . $activeDbVersion . "]", "id" );
            if ( array_count_values( $scriptNodes ) > 0 ) {
                global $wpdb;
                $prefix = $wpdb->prefix . self::SLOG_DB_PREFIX;
                foreach ( $scriptNodes as $currNode ) {
                    $wpdb->query( str_replace(
                        "%object_prefix%", $prefix,
                        $currNode ) );
                }
            }
            update_option( self::SLOG_DB_VERSION_OPTION_NAME, self::SLOG_LATEST_DB_VERSION );
        }
    }

    static function get_db_version () {
        return get_option( self::SLOG_DB_VERSION_OPTION_NAME, 0 );
    }

    public function __toString() {
        return "Scouters_Log_Database";
    }
}
